package com.ruoyi.web.controller.system;

import java.math.BigDecimal;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.system.domain.Skzh;
import com.ruoyi.system.domain.Tidetails;
import com.ruoyi.system.domain.bo.SlmxBo;
import com.ruoyi.system.domain.bo.TiBo;
import com.ruoyi.system.domain.vo.TiVo;
import com.ruoyi.system.service.ISkzhService;
import com.ruoyi.system.service.ISlmxService;
import com.ruoyi.system.service.ITidetailsService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.Ti;
import com.ruoyi.system.service.ITiService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 提现记录Controller
 *
 * @author ruoyi
 * @date 2025-05-12
 */
@RestController
@RequestMapping("/system/ti")
public class TiController extends BaseController
{
    @Autowired
    private ITiService tiService;
    @Autowired
    private ISkzhService skzhService;
    @Autowired
    private ITidetailsService tidetailsService;
    @Autowired
    private ISlmxService slmxService;

    /**
     * 查询提现记录列表
     */
    @PreAuthorize("@ss.hasPermi('system:ti:list')")
    @GetMapping("/list")
    public TableDataInfo list(Ti ti)
    {
        startPage();
        SysUser sysUser = getLoginUser().getUser();
        boolean contains3OR4 = sysUser.getRoles().stream().anyMatch(v->v.getRoleId()==3L || v.getRoleId()==4L);
        if(contains3OR4){
            ti.setUserId(getUserId());
        }
        List<TiBo> list = tiService.selectTiList(ti);
        return getDataTable(list);
    }

    @PreAuthorize("@ss.hasPermi('system:ti:add')")
    @GetMapping("/withdrawal")
    public AjaxResult withdrawal()
    {
        String state="1";
        String bank=null;
        BigDecimal pendingMoney=new BigDecimal("0");
        Long tiId=null;
        Long deptId = getDeptId();
        Long userId = getUserId();
        LambdaQueryWrapper<Skzh> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.select(Skzh::getSkzhId,Skzh::getReviewStatus,Skzh::getWithdrawalStatus,Skzh::getBank);
        lambdaQueryWrapper.eq(Skzh::getDeptId,deptId);
        Skzh  dbSkzh= skzhService.getOne(lambdaQueryWrapper);
        if(dbSkzh==null && state.equals("1")){
            state="2";
        }
        if(dbSkzh!=null){
            bank=dbSkzh.getBank();
        }

        if(dbSkzh!=null && dbSkzh.getReviewStatus().equals("1") && state.equals("1")){
            state="3";
        }
        if(dbSkzh!=null && dbSkzh.getWithdrawalStatus().equals("2") && state.equals("1")){
            LambdaQueryWrapper<Ti> lambdaQueryWrapper1=new LambdaQueryWrapper<>();
            lambdaQueryWrapper1.select(Ti::getTotalMoeny,Ti::getTiId);
            lambdaQueryWrapper1.eq(Ti::getUserId,userId);
            lambdaQueryWrapper1.eq(Ti::getStatus,"1");
            Ti dbTi = tiService.getOne(lambdaQueryWrapper1);
            if(dbTi!=null){
                pendingMoney=dbTi.getTotalMoeny();
                tiId=dbTi.getTiId();
            }
            state="4";
        }
        BigDecimal balanceMoney = tiService.withdrawableBalance(userId);
        BigDecimal totalMoney = tiService.withdrawnTotal(userId);
        if(balanceMoney.compareTo(BigDecimal.ZERO)==0 && state.equals("1")){
            state="5";
        }

        return AjaxResult.success().put("balanceMoney",balanceMoney.toString()).put("totalMoney",totalMoney.toString()).put("pendingMoney",pendingMoney.toString()).put("state",state).put("bank",bank).put("tiId",tiId);
    }

    /**
     * 导出提现记录列表
     */
//    @PreAuthorize("@ss.hasPermi('system:ti:export')")
//    @Log(title = "提现记录", businessType = BusinessType.EXPORT)
//    @PostMapping("/export")
//    public void export(HttpServletResponse response, Ti ti)
//    {
//        List<Ti> list = tiService.selectTiList(ti);
//        ExcelUtil<Ti> util = new ExcelUtil<Ti>(Ti.class);
//        util.exportExcel(response, list, "提现记录数据");
//    }




    @PreAuthorize("@ss.hasPermi('system:ti:query')")
    @GetMapping(value = "/{tiId}")
    public AjaxResult getInfo(@PathVariable("tiId") Long tiId)
    {
        TiBo tiBo = tiService.selectTiByTiId(tiId);
        Skzh skzh = skzhService.selectSkzhBySkzhId(tiBo.getSkzhId());
        tiBo.setAccount(skzh.getAccount());
        tiBo.setBank(skzh.getBank());
        tiBo.setOpenBank(skzh.getOpenBank());

        return success(tiBo);
    }

    /**
     * 获取提现记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:ti:query')")
    @GetMapping("/listSlmx")
    public TableDataInfo listSlmx(Long tiId)
    {
        LambdaQueryWrapper<Tidetails> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.select(Tidetails::getSlmxId);
        lambdaQueryWrapper.eq(Tidetails::getTiId,tiId);
        List<Tidetails> list = tidetailsService.list(lambdaQueryWrapper);
        Long [] ids=list.stream().map(v->v.getSlmxId()).toArray(Long[]::new);
        startPage();
        List<SlmxBo> slmxBos = slmxService.selectSlmxs(ids);
        return getDataTable(slmxBos);
    }

    /**
     * 新增提现记录
     */
    @PreAuthorize("@ss.hasPermi('system:ti:add')")
    @Log(title = "提现记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add()
    {
        Ti ti=new Ti();
        Long deptId = getDeptId();
        Long userId = getUserId();
        LambdaQueryWrapper<Skzh> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.select(Skzh::getSkzhId,Skzh::getReviewStatus,Skzh::getWithdrawalStatus,Skzh::getBank);
        lambdaQueryWrapper.eq(Skzh::getDeptId,deptId);
        Skzh  dbSkzh= skzhService.getOne(lambdaQueryWrapper);
        if(dbSkzh==null){
            throw new RuntimeException("还没有收款账号");
        }
        if(dbSkzh.getReviewStatus().equals("1")){
            throw new RuntimeException("收款账号审核中");
        }
        if(dbSkzh.getWithdrawalStatus().equals("2")){
            throw new RuntimeException("收款账号正在提现中");
        }
        BigDecimal balanceMoney = tiService.withdrawableBalance(userId);
        if(balanceMoney.compareTo(BigDecimal.ZERO)==0){
            throw new RuntimeException("暂无余额提现");
        }
        ti.setSkzhId(dbSkzh.getSkzhId());
        ti.setUserId(getUserId());
        ti.setTiNo("MY"+IdWorker.getIdStr());
        ti.setTotalMoeny(balanceMoney);
        Skzh skzh=new Skzh();
        skzh.setSkzhId(dbSkzh.getSkzhId());
        skzh.setWithdrawalStatus("2");
        return toAjax(tiService.insertTi(ti,skzh));
    }

    /**
     * 修改提现记录
     */
    @PreAuthorize("@ss.hasPermi('system:ti:edit')")
    @Log(title = "提现记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TiVo tiVo)
    {
        LambdaQueryWrapper<Ti> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.select(Ti::getTiId,Ti::getSkzhId);
        lambdaQueryWrapper.eq(Ti::getTiId,tiVo.getTiId());
        lambdaQueryWrapper.eq(Ti::getStatus,"1");
        Ti dbTi = tiService.getOne(lambdaQueryWrapper);
        if(dbTi==null){
            throw  new RuntimeException("该提现状态已更新,请重新刷新");
        }
        if(tiVo.getIsSend().equals("1")){
            System.out.println("发送短信");
        }
        Ti ti = tranferBo(tiVo, Ti.class);
        ti.setSkzhId(dbTi.getSkzhId());
        return toAjax(tiService.updateTi(ti));
    }

    /**
     * 删除提现记录
     */
    @PreAuthorize("@ss.hasPermi('system:ti:remove')")
    @Log(title = "提现记录", businessType = BusinessType.DELETE)
	@DeleteMapping("/{tiIds}")
    public AjaxResult remove(@PathVariable Long[] tiIds)
    {
        return toAjax(tiService.deleteTiByTiIds(tiIds));
    }
}
